
//var api_server = 'http://127.0.0.1:15151'
var remote = 'https://user.hackerstack.top'

function login_ok() {
    var get_result = false;
    try {
        var json = JSON.parse(document.cookie);
        if (json.user != null && json.pwd != null)
        {
            var json = JSON.parse(document.cookie);
            var username =  json.user;
            var password = json.pwd;
            
            var xhr = new XMLHttpRequest();
            xhr.open("POST" , remote+"/login",false);
            xhr.send(username+"\n"+password);
            
            // 返回的是 Json字符串，自己去处理,默认的信息是 {"message":"login successful."}
            var json_content = xhr.responseText;
            var json = JSON.parse(json_content);
            if (String(json.message).toLowerCase().includes("login successful.")) {
                document.cookie = "{\"user\" : \""+username+"\" , \"pwd\" : \""+password+"\"}";
  
                var top = document.getElementById('a_top');
                top.className = 'top_btn'
                var login_btn = document.getElementById('login');
                login_btn.innerText = "登录: "+username;
                return true;
            } else {
                return false; 
            }
        }else{
            document.cookie = "{\"user\":\"\",\"pwd\":\"\"}";
        }
        return get_result;
    }catch (e) {
        return get_result;
    }
}


function auto_login() {

    try{
        var json = JSON.parse(document.cookie);
        var username =  json.user;
        var password = json.pwd;
        
        var xhr = new XMLHttpRequest();
        xhr.open("POST" , remote+"/login",true);
        xhr.send(username+"\n"+password);
        
        xhr.onload=function(){
        // 返回的是 Json字符串，自己去处理,默认的信息是 {"message":"login successful."}
        var json_content = xhr.responseText;
        var json = JSON.parse(json_content);
        if (String(json.message).toLowerCase().includes("login successful.")) {
            document.cookie = "{\"user\" : \""+username+"\" , \"pwd\" : \""+password+"\"}";
            
            var login_btn = document.getElementById('login');
            login_btn.innerText = "登录: "+username;
            login_btn.onclick = function() {
                window.location.href = "./user.html";
            }
            var top = document.getElementById('a_top');
            var exit_login = document.createElement('button');
            exit_login.className = 'b'
            exit_login.onclick=function() {
                document.cookie = null;
                window.location.href='./index.html'
            }
            exit_login.innerText = '退出登录'
            top.appendChild(exit_login);
            return true;
        } else {
            return false; 
        }
        }
    } catch(e) {
        document.cookie = '';
        document.cookie = "{\"user\" : \"\" , \"pwd\" : \"\"}";
        return false;
    }
}

window.onload = function() {
    auto_login()
}
